package boboUtil;

//此类提供 Collection 接口的骨干实现，以最大限度地减少了实现BoboCollection接口所需的工作。

import java.util.Arrays;

public abstract class BoboAbstractCollection<E> implements BoboCollection<E>{

    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    @Override
    public String toString() {
        return super.toString();
    }

    public boolean isEmpty() {
        return size() == 0;
    }


    public boolean remove(Object obj) {
        BoboIterator<E> it = iterator();
        if (obj == null){
            while (it.hasNext()){
                if (it.next() == null){
                    it.remove();
                    return true;
                }
            }
        } else {
            while (it.hasNext()){
                if (obj.equals(it.next())){
                    it.remove();
                    return true;
                }
            }
        }
        return false;
    }

    public boolean removeAll(BoboCollection<?> c) {
        BoboIterator<E> it = iterator();
        boolean modified = false;
        while (it.hasNext()){
            if (c.contains(it.next())){
                it.remove();
                modified = true;
            }
        }
        return false;
    }

    public void clear() {
        BoboIterator<E> it = iterator();
        while (it.hasNext()){
            it.next();
            it.remove();
        }
    }

    public boolean contains(Object obj) {
        BoboIterator<E> it = iterator();
        if (obj == null){
            while (it.hasNext()){
                if (it.next() == null) return true;
            }
        } else {
            while (it.hasNext()){
                if (it.next().equals(obj)) return true;
            }
        }
        return false;
    }

    public boolean containsAll(BoboCollection<?> c) {
       BoboIterator<?> it = c.iterator();
       while (it.hasNext()){
           if (!contains(it.next()))
               return false;
       }
       return true;
    }

    public Object[] toArray() {
        Object[] r = new Object[size()];
        BoboIterator it = iterator();
        for (int i=0; i<r.length; i++){
            if (!it.hasNext()){
                return Arrays.copyOf(r, i);
            }
            r[i] = it.next();
        }

        return it.hasNext() ? finishToArray(r, it) : r;
    }

    public <T> T[] toArray(T[] a) {
        return null;
    }

    private static <T> T[] finishToArray(T[] r, BoboIterator<?> it) {
        int i = r.length;
        while (it.hasNext()) {
            int cap = r.length;
            if (i == cap) {
                int newCap = cap + (cap >> 1) + 1;
                r = Arrays.copyOf(r, newCap);
            }
            r[i++] = (T)it.next();
        }
        // trim if overallocated
        return (i == r.length) ? r : Arrays.copyOf(r, i);
    }

    public boolean add(E e) {
        throw new UnsupportedOperationException();
    }
}
